import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  // .env.development中定义了VUE_APP_BASE_API，其值为dev-api，我们可以去掉它   !!!!!!!!!!!!!!
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout 请求超时时间，可以设置长点，这里10秒    !!!!!!!!!!!!!!
})

// request interceptor 配置请求拦截器    !!!!!!!!!!!!!!
service.interceptors.request.use(
  config => {
    // store.getters.token为src/store/getters.js中的定义的token，其实就是user模块里定义的token   !!!!!!!!!!!!!!
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // 为每次请求的请求头中都携带上自定义token  !!!!!!!!!!!!!!
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor 配置响应拦截器   !!!!!!!!!!!!!!
service.interceptors.response.use(
  response => {
    const res = response.data
    // response表示成功调到了后端接口，response.status为200表示成功调到了后端接口    !!!!!!!!!!!!!!
    if (response.status && response.status === 200) {
      // 业务逻辑错误  !!!!!!!!!!!!!!
      // response.data.code为本次请求的响应码，500表示报错，401表示未登录，403表示未授权    !!!!!!!!!!!!!!
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;    !!!!!!!!!!!!!!
      if (res.code === 500 || res.code === 401 || res.code === 403) {
        // to re-login
        MessageBox.confirm(res.message, '提示信息', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      } else {
        // 响应是成功的，登录的时候会将响应过来的数据返回给modules/user.js的login()  !!!!!!!!!!!!!!
        return Promise.resolve(res)
      }
    } else {
      // 说明本次请求的statu为200，发送不成功。
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
